package com.weibo4terios.logic;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.weibo.net.AccessToken;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;
import com.weibo4terios.conts.CommonStrs;
import com.weibo4terios.dao.Paging;
import com.weibo4terios.dao.Status;
import com.weibo4terios.dao.User;
import com.weibo4terios.http.WeiboResponse;
import com.weibo4terios.ui.HomeActivity;
import com.weibo4terios.ui.LoginActivity;
import com.weibo4terios.ui.util.IWeiboActivity;


/**
 * MainService.java 2012-9-27 下午12:14:11
 * 
 * @author Wang Tengrui (核心控制类) 完成程序调度 接收UI层数据(任务)，完成业务逻辑，返回信息，更新UI
 *         在后台运行(继承自Service类) 线程(实现Runnable接口) 不断侦听UI传过来任务消息
 */
public class MainService extends Service implements Runnable {
	public static Weibo mWeibo;
	public static User nowUser;// 当前用户

	// 把Activity添加到allActivity数组列表中，以便管理和调用
	public static ArrayList<Activity> allActivity = new ArrayList<Activity>();

	// 将所有任务添加到allTask数组列表中，以便管理和调用
	public static ArrayList<Task> allTask = new ArrayList<Task>();

	// 遍历查找需要的Activity
	public static Activity getActivityByName(String name) {
		for (Activity activity : allActivity) {
			if (activity.getClass().getName().indexOf(name) >= 0) {
				Log.i("status", ACTIVITY_SERVICE.getClass().getName().toString());
				return activity;
			}
		}
		return null;
	}

	// 添加Task到数组列表中
	public static void addTask(Task task) {
		allTask.add(task);
	}

	public boolean isRun = true;// 线程开关

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case CommonStrs.TASK_USER_LOGIN:// 通知Login页面 登陆成功
				IWeiboActivity loginActivity = (IWeiboActivity) MainService.getActivityByName("LoginActivity");
				loginActivity.refresh(Integer.valueOf(LoginActivity.REFRESH_LOGIN), msg.obj);
				break;

			case CommonStrs.TASK_GET_USER_HOMETIMEINLINE:// 获取主页内容
				IWeiboActivity homeActivity = (IWeiboActivity) MainService.getActivityByName("HomeActivity");
				homeActivity.refresh(HomeActivity.REFRESH_WEIBO, msg.obj);
				break;

			case CommonStrs.TASK_GET_USER_MENTIONS:// 获取at当前用户的微博
				
				break;

			case CommonStrs.TASK_GET_USER_COMMENTS://获取评论
				
				break;
				
			case CommonStrs.TASK_SEARCH_WEIBO:
				
				break;
			}
		}
	};

	private void doTask(Task task) {
		Message message = handler.obtainMessage();
		message.what = task.getTaskID();
		switch (task.getTaskID()) {
		case CommonStrs.TASK_USER_LOGIN:// 执行登录任务
			String token = (String) task.getTaskParam().get("token");
			String secret = CommonStrs.CONSUMER_SECRET;
			AccessToken accessToken = new AccessToken(token, secret);
			mWeibo = Weibo.getInstance();
			mWeibo.setAccessToken(accessToken);
			WeiboParameters bundle1 = new WeiboParameters();
			bundle1.add("uid", (String) task.getTaskParam().get("uid"));
			WeiboResponse mWeiboResponse1 = WeiboResponse.getInstance(getActivityByName("LoginActivity"));
			try {
				nowUser = new User(mWeiboResponse1.getUserInfo(bundle1));
			} catch (WeiboException e1) {
				Log.e("TASK_USER_LOGIN", "获取当前登录用户信息 失败");
				e1.printStackTrace();
			}
			message.obj = nowUser;

			break;
		case CommonStrs.TASK_GET_USER_HOMETIMEINLINE:// 得到刷新主页面信息的任务
			Paging paging1 = new Paging((Integer) task.getTaskParam().get("nowPage"), (Integer) task.getTaskParam().get("pageSize"));
			WeiboParameters bundle2 = new WeiboParameters();
			bundle2.add("source", Weibo.getAppKey());
			bundle2.add("page", String.valueOf(paging1.getPage()));
			bundle2.add("count", String.valueOf(paging1.getCount()));
			List<Status> allWeibo1 = null;
			WeiboResponse mWeiboResponse2 = WeiboResponse.getInstance(getActivityByName("HomeActivity"));
			try {
				allWeibo1 = Status.statusList(mWeiboResponse2.getHomeTimeLine(bundle2));
				message.obj = allWeibo1;
			} catch (WeiboException e) {
				Log.e("TASK_GET_USER_HOMETIMEINLINE", "获取当前登录用户及其所关注用户的最新微博 失败");
				e.printStackTrace();
			}
			break;
		case CommonStrs.TASK_GET_USER_MENTIONS:// 获取at当前用户的微博
		
			break;
		case CommonStrs.TASK_GET_USER_COMMENTS://获取评论

			break;
		case CommonStrs.TASK_SEARCH_WEIBO:// 搜索微博

			break;
		}
		handler.sendMessage(message);// 发送消息
		allTask.remove(task);// 任务处理完毕，移除该任务
	}

	@Override
	public void onCreate() {
		super.onCreate();
		isRun = true;// 启动线程
		Thread thread = new Thread(this);
		thread.start();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.stopSelf();
		isRun = false;
	}

	@Override
	public void run() {
		while (isRun) {
			Task lastTask = null;
			synchronized (allTask) {
				if (allTask.size() > 0) {
					lastTask = allTask.get(0);
					doTask(lastTask);
				}
			}
			// 每隔一秒侦查是否是否还有任务
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	/**
	 * 退出应用
	 */
	public static void exitApp(Context context) {
		context.stopService(new Intent("com.weibo4terios.logic.MainService"));// 停止主服务
		android.os.Process.killProcess(android.os.Process.myPid());
		for (Activity activity : allActivity) {
			activity.finish();
		}
	}

	/**
	 * 网络连接异常 按钮显示信息未定义
	 */
	public static void alertNetError(final Context context) {
		AlertDialog.Builder alertError = new AlertDialog.Builder(context);
		alertError.setTitle("");
		alertError.setMessage("");
		alertError.setNegativeButton("", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				exitApp(context);
			}
		});
		alertError.setPositiveButton("", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				context.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
			}
		});
		alertError.create().show();

	}
}
